package com.cci.kangdao.fieldService.service.impl;

import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.fieldService.dao.FieldServiceNotifyRecordDao;
import com.cci.kangdao.fieldService.model.FieldServiceNotifyRecord;
import com.cci.kangdao.fieldService.service.FieldServiceChannelService;
import com.cci.kangdao.fieldService.service.FieldServiceNoticeService;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author William Du
 * @date 2020/3/4
 */
@Service
public class FieldServiceNoticeServiceImpl implements FieldServiceNoticeService {

    private static final Logger logger = Logger.getLogger(FieldServiceNoticeService.class);

    @Resource
    private LoginDao loginDao;

    @Resource
    private FieldServiceNotifyRecordDao fieldServiceNotifyRecordDao;

    @Override
    public void sendSMS(Long orderId, Long userId, String phone, String content, Long creator) {
        if(StringUtils.isEmpty(phone) && !NumberUtils.isPositiveNum(userId)){
            logger.error("调用发送短信方法出错，userId和phone字段不能同时为空");
            return;
        }
        if(StringUtils.isEmpty(phone)){
            UserT userT = loginDao.getUserByUserId(userId);
            phone = userT.getPhone();
        }
        if(!NumberUtils.isPositiveNum(userId)){
            List<UserT> userTList = loginDao.getUserByPhone(phone);
            if(CollectionUtils.isNotEmpty(userTList)){
                userId = userTList.get(0).getId();
            }
        }

        FieldServiceNotifyRecord record = new FieldServiceNotifyRecord();
        record.setOrderId(orderId);
        record.setCategory(1);
        record.setSendType(1);
        record.setReceiverId(userId);
        record.setContent(content);
        record.setIsRead(0);
        record.setFlag(0);
        record.setCreator(creator);
        record.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        sendSMS(phone,record);
        fieldServiceNotifyRecordDao.insertSelective(record);
    }

    private void sendSMS(String phone,FieldServiceNotifyRecord record){
        String sendResult = SmsUtils.sendMessage(phone,record.getContent());
        if(sendResult.startsWith("ERR")){
            record.setStatus(0);
            record.setException(sendResult);
        }else{
            record.setStatus(1);
        }
    }





}
